import React, { useRef, useEffect } from "react"
import { GridView, ScrollView, StickyHeader, StickySection, Text, View } from "@tarojs/components"
import Taro, { useRouter, getCurrentInstance, useReady } from "@tarojs/taro"
import GpContainer from "@/components/GpContainer"
import GpVerticelLine from "@/components/GpVerticelLine"
import { useSetState } from "@/utils/hooks"
import clsx from "clsx"
import GpNoteItem from "../components/GpNoteItem"
import styles from "./index.module.scss"
import { getNoteTagDetail, getNoteTagDetailNoteList } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import GpScrollLoading from "@/components/GpScrollLoading"
import GpNavbar from "@/components/GpNavbar"
import { isSkyline } from "@/utils/core"

type IState = {
  currentFilter: number
  list: IApiRelative.IGetNoteTagDetailNoteList.IGetNoteTagDetailNoteListItem[]
  detail: IApiRelative.IGetNoteTagDetail.INoteTagItem
  current: number
  hasMore: boolean
  skyline: boolean
  refresherTriggered: boolean
}
type IParams = {
  /** 笔记标签id */
  id: string
}
/**
 * @component 笔记标签详情
 * @example id=3285
 */
export default function NoteTag() {
  const router = useRouter<IParams>()
  const filters = useRef<IOptionLike<number>[]>([
    { value: 0, label: "最热" },
    { value: 1, label: "最新" }
  ])
  const [state, setState, stateRef] = useSetState<IState>(
    {
      currentFilter: filters.current[0].value,
      list: [],
      detail: {} as any,
      current: 1,
      hasMore: true,
      skyline: isSkyline(),
      refresherTriggered: false
    },
    true
  )
  const scrollCtx = useRef<any>()
  useEffect(() => {
    fetchTagDetail()
    searchNotes()
  }, [])
  useReady(() => {
    Taro.createSelectorQuery()
      .select("#listScrollview")
      .node()
      .exec(res => {
        scrollCtx.current = res[0].node
        scrollCtx.current.enhanced = true
      })
  })
  function handleReachBottom() {
    if (stateRef.current?.hasMore) {
      setState({ current: stateRef.current.current + 1 })
      searchNotes()
    }
  }
  function handlePullDownRefresh() {
    setState({ current: 1 })
    searchNotes().finally(() => {
      setState({
        refresherTriggered: false
      })
      if (scrollCtx.current) {
        scrollCtx.current.closeRefresh()
      }
    })
  }
  function fetchTagDetail() {
    return getNoteTagDetail({ id: router.params.id }).then(res => {
      if (requestIsFullfilled(res)) {
        setState({
          detail: res.data.data
        })
      }
    })
  }
  function handleChangeFilter(filter: number) {
    if (state.currentFilter === filter) return
    setState({
      currentFilter: filter,
      current: 1,
      hasMore: true
    })
    searchNotes()
  }
  function searchNotes() {
    Taro.showLoading({ title: "加载中..." })
    return getNoteTagDetailNoteList(
      {
        id: router.params.id
      },
      {
        pagination: {
          current: stateRef.current!.current,
          pageSize: 10
        },
        search: {},
        sort: {
          predicate: stateRef.current!.currentFilter === 1 ? "updatedTime" : "",
          reverse: stateRef.current!.currentFilter === 1
        }
      }
    )
      .then(res => {
        if (requestIsFullfilled(res)) {
          const { list, pagination } = res.data.data
          setState({
            list: pagination.current === 1 ? list : [...stateRef.current!.list, ...list],
            hasMore: pagination.current < pagination.pageCount
          })
        }
      })
      .finally(() => Taro.hideLoading())
  }
  function renderNavigation() {
    return (
      <GpNavbar
        className="relative"
        navigationBarPlaceholder={false}
        navigationBarBackgroundColor="#ffffff"
        navigationBarTitleText="笔记标签"
      />
    )
  }
  return (
    <GpContainer
      className="h-full min-h-screen flex flex-col box-border"
      style={{
        backgroundColor: "#F7F7F7"
      }}
      shareConfig={{ title: "笔记标签-" + state.detail.name }}
    >
      {renderNavigation()}
      <View className={styles.noteTag}>
        <ScrollView
          style={{
            width: "100%",
            height: "100%",
            boxSizing: "border-box"
          }}
          scrollY
          type="custom"
          showScrollbar={false}
          onScrollToLower={handleReachBottom}
          refresherEnabled
          refresherTriggered={state.refresherTriggered}
          onRefresherRefresh={handlePullDownRefresh}
          refresherBackground="transparent"
        >
          <StickySection>
            <View className={styles.tagInfo}>
              <Text className={styles.tagTitle}>#{state.detail.name}#</Text>
              <View className={styles.infos}>
                <Text className={styles.desc}>{state.detail.noteCount}篇内容</Text>
                <GpVerticelLine width={2} height={28} color="#999999" />
                <Text className={styles.views}>{state.detail.viewCount}次浏览</Text>
              </View>
            </View>
            <StickyHeader>
              <View className={styles.filters}>
                {filters.current.map(l => (
                  <View
                    className={clsx(styles.filter, {
                      [styles.filterActive]: state.currentFilter === l.value
                    })}
                    key={l.value}
                    onClick={() => handleChangeFilter(l.value)}
                  >
                    {l.label}
                  </View>
                ))}
              </View>
            </StickyHeader>
          </StickySection>
          <StickySection>
            <GridView
              type="masonry"
              crossAxisCount={2}
              mainAxisGap={5}
              crossAxisGap={5}
              padding={[0, 16, 0, 16]}
            >
              {state.list.map(l => (
                <GpNoteItem
                  skyline={state.skyline}
                  key={l.id}
                  noteItem={{
                    id: l.id,
                    actionFlag: false,
                    avatar: l.createdByHead,
                    image: l.thumbnail,
                    fileType: l.fileType,
                    liked: l.isSelfLike,
                    likes: l.likeCount,
                    name: l.createdByName,
                    title: l.title,
                    videoFlag: false,
                    content: l.description
                  }}
                  clickToNavigation
                />
              ))}
            </GridView>
            {state.hasMore ? (
              <GpScrollLoading />
            ) : (
              <View className="text-light text-24px text-center mt-24px">--没有更多喽--</View>
            )}
          </StickySection>
        </ScrollView>
      </View>
    </GpContainer>
  )
}
